import os
import requests
import json
import sys
import time

PUSH_PLUS_TOKEN = ''  # push+ 微信推送的用户令牌
confFile='./last_conf.json'

os.chdir(os.path.abspath(os.path.dirname(sys.argv[0])))


if os.getenv('PUSH_PLUS_TOKEN'):
    PUSH_PLUS_TOKEN = os.getenv('PUSH_PLUS_TOKEN')
if not os.getenv('PVE_NODE_API'):
    print('请先配置PVE_NODE_API环境变量')
    print('变量值例如:http://[PVE服务器ip]:12000/status?id=[网心云虚拟机id]')
    exit()
PVE_NODE_API=os.getenv('PVE_NODE_API')
print(PUSH_PLUS_TOKEN);

def post_msg(url: str, data: dict) -> bool:
    response = requests.post(url, data=data)
    code = response.status_code
    if code == 200:
        return True
    else:
        return False


def PushPlus_send(token, title: str, desp: str = '', template: str = 'txt') -> bool:
    url = 'http://www.pushplus.plus/send'
    data = {
        'token': token,  # 用户令牌
        'title': title,  # 消息标题
        'content': desp,  # 具体消息内容，根据不同template支持不同格式
        'template': template,  # 发送消息模板
    }

    return post_msg(url, data)

def push(title,msg):
    if PUSH_PLUS_TOKEN:
        PushPlus_send(PUSH_PLUS_TOKEN, title, msg)


def is_same_day(timestamp1, timestamp2):
    tz_offset = 8 * 3600  # +8 为东八区时区偏移，转换为秒数

    # 计算时间戳对应的日期
    date1 = (int(timestamp1) + tz_offset) // (24 * 3600)
    date2 = (int(timestamp2) + tz_offset) // (24 * 3600)

    return date1 == date2

    # print(is_same_day(1683902191,1683907199))
    # print(is_same_day(1683902191,1683907200))
    # print(is_same_day(1683902191,1683820800))
    # print(is_same_day(1683902191,1683820799))

def format_bytes(size):
    power = 2**10  # 1 KB = 1024 B

    # 定义单位列表
    units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']

    # 计算对应的单位索引
    unit_index = 0
    while size >= power and unit_index < len(units)-1:
        size /= power
        unit_index += 1

    # 格式化为字符串并返回
    return f'{round(size, 2)} {units[unit_index]}'



def main():
    
    #json.load(f=)
    lastDayData={"netin":0,"netout":0,"status":"not running",'recoredTime':0,"uptime":0}
    try:
        with open(confFile,'r') as f:
            lastDayData=json.load(fp=f)
    except Exception as e:
        print(e)
    try:
        res=requests.get(PVE_NODE_API)
        res=res.json()
        res['recoredTime']=int(time.time())
        #saveData=res.json()
        #print(lastDayData)
        #print(res)
        if(res['uptime']>lastDayData['uptime'] and lastDayData['uptime']>0):
            i_out=format_bytes(res['netout']-lastDayData['netout']);
            i_in=format_bytes(res['netin']-lastDayData['netin']);
        else:
            i_out=format_bytes(res['netout']);
            i_in=format_bytes(res['netin']);
            lastDayData['uptime']=res['uptime']-1
            lastDayData['recoredTime']=res['recoredTime']
            print('正在重载数据')

            
            
            

        if is_same_day(res['recoredTime'],lastDayData['recoredTime']):
            print(f'今日上传:{i_out},下载:{i_in}')
        else:
            print(f'昨日上传:{i_out},下载:{i_in}')
            push('网心云流量监控_昨日流量',f"上传:{i_out},下载:{i_in}");
            lastDayData=res
        
        with open(confFile,'w') as f:
            print('正在保存数据')
            json.dump(lastDayData,fp=f)
        
    except Exception as e:
        print(e)
        push('网心云监控',"提示：监控已失效，可能是API网关未运行");

main();